/**医生讲堂详情入口
 * Created by alice on 2016/7/11.
 */
require.config({
    baseUrl:'../js',
    paths:{
        "getData":"Util/getData",
        "config":"common/config",
        "components":"common/components",
        "common":"common/common",
        "jquery":"lib/jquery.min",
        "wx":"lib/jweixin-1.0.0"
    },
    shim : {
        "components": { deps : ["jquery"] }
    },
    urlArgs: "v=" + (new Date()).getTime()//以禁用浏览器缓存,上线后注释掉
});
require(['jquery','getData','config','common','components','wx'],function($,getData,config,common,components,wx){
    //获取gm obj
    var gm=common.gm;
    var token=gm.para.get(window.location.href,"token");
    var vedioid=gm.para.get(window.location.href,"favoriteUuid");
    var getUrl=location.href.split('#')[0];
    delAllCookie();
    //删除cookie中所有定变量函数    
       function delAllCookie(){
            var myDate=new Date();    
            myDate.setTime(-1000);//设置时间    
            var data=document.cookie;    
            var dataArray=data.split("; ");    
            for(var i=0;i<dataArray.length;i++){    
                 var varName=dataArray[i].split("=");    
                 document.cookie=varName[0]+"=''; expires="+myDate.toGMTString();    
            }    
                          
      } 
    /*if(gm.common.isWeiXin()){//判断是否是微信
        getData.getJson({
            page:"content",
            inter:"getSignature",
            data:{url:getUrl},
            callback:function(data){
                if(data.code=="2000"){
                    getSignMessCollbak(data);
                }
            }
        })
    }*/
    /**
     * 微信分享的回调
     * @param data
     */
    /*function getSignMessCollbak(data){
        //微信二次分享
        var d=data.value;
        var appId= d.appid;
        var timestamp= d.timestamp;
        var nonceStr= d.nonceStr;
        var signature= d.signature;
        var title=gm.para.get(window.location.href,"title");
        title = decodeURIComponent(title);
        var imgUrl=window._interfaceImgPath+""+gm.para.get(window.location.href,"img");
        var desc=gm.para.get(window.location.href,"desc");
        desc = decodeURIComponent(desc);
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: appId, // 必填，公众号的唯一标识
            timestamp:timestamp, // 必填，生成签名的时间戳
            nonceStr: nonceStr, // 必填，生成签名的随机串
            signature: signature,// 必填，签名，见附录1
            jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(function(){
            //分享到朋友圈
            wx.onMenuShareTimeline({
                title: title, // 分享标题
                link: getUrl, // 分享链接
                imgUrl: imgUrl, // 分享图标
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
            //分享给朋友
            wx.onMenuShareAppMessage({
                title: title, // 分享标题
                desc: desc, // 分享描述
                link: getUrl, // 分享链接
                imgUrl: imgUrl, // 分享图标
                type: '', // 分享类型,music、video或link，不填默认为link
                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                success: function () {
                    // 用户确认分享后执行的回调函数
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
            });
        });
    }*/


    //获取视频
    getData.getJson({
        page:"doctor",
        loading:true,
        inter:"getDoctorCommonVideoInfo",
        data:{token:token,videoId:vedioid},
        callback:function(data){
            var getdetimg=gm.common.isObjUsable(data.value.image);
            getdetimg=getdetimg?window._interfaceImgPath+""+data.value.image:"../imgs/patientLogo.png";
            if(gm.common.isWeiXin()){
                gm.common.userShare({
                    title:data.value.videoName,
                    imgUrl:getdetimg,
                    desc:data.value.videoIntroduction,
                    url:getUrl
                });//分享调用
            }
            getVedio(data);
        }
    });
    function getVedio(data){
        if(!data){
            components.alert("服务器出错!");
            return;
        }
        if(data.code=="2000"){
            //绑定视频列表
            var arr = [];
            var getimg=data.value.image;
            var image=gm.common.isObjUsable(getimg)?window._interfaceImgPath+""+getimg:window.___defaultImage;
            getvedioimg=image;
            var tmp = '<h2>{videoName}</h2>\
						<p>时间： <span class="color">{createTime}</span></p>\
						<p>主讲人：<span class="color">{userName}</span></p>\
						<p><span class="color">{userIntroduce}</span></p>\
						<p>课程简介：<span class="color">{videoIntroduction}</span></p>';

            var mp4,videoBox,isAndroid = navigator.userAgent.toLocaleLowerCase().indexOf('android') > -1 || navigator.userAgent.toLocaleLowerCase().indexOf('adr') > -1;

            if(data.value.videoAddress){
                videoBox = document.createElement("div");
                videoBox.className = "videoBox";
                if(isAndroid &&!gm.common.isWeiXin()){
                    videoBox.style.cssText = "background:#000 url(" + getvedioimg + ") no-repeat;background-size:100%;";
                    mp4 = document.createElement("div");
                    mp4.style.cssText = "position:absolute;left:50%;top:50%;margin:-3.27rem 0 0 -3.27rem;width:6.54rem;height:6.54rem;background:url(../imgs/video_play.png) no-repeat;background-size:100%;";
                    $(mp4).on("touchend",function(){
                        var vTitle=data.value.videoName;
                        vTitle=gm.common.isObjUsable(vTitle)>0?vTitle:"V医讲堂";
                        gm.pul.toUrl("goodm://fullPage/"+data.value.videoAddress+"|"+ vTitle);
                        //记录播放次数
                        if(!gm.common.isWeiXin() && gm.common.isObjUsable(token)){
                            getData.getJson({
                                page:"user",
                                inter:"recordPlayNum",
                                data:{
                                    token:token,
                                    id:vedioid
                                },
                                callback:function(data){

                                }
                            })
                        }
                        return false;
                    });
                }else{
                    mp4 = document.createElement("video");
                    mp4.id = "video";
                    mp4.setAttribute("poster",getvedioimg);
                    mp4.setAttribute("src",data.value.videoAddress);
                    mp4.setAttribute("preload",false);
                }
                videoBox.appendChild(mp4);
                 mp4.onplay = function(){
                     //记录播放次数
                     if(!gm.common.isWeiXin() && gm.common.isObjUsable(token)){
                         getData.getJson({
                             page:"user",
                             inter:"recordPlayNum",
                             data:{
                                 token:token,
                                 id:vedioid
                             },
                             callback:function(data){

                             }
                         })
                     }
                 	$(mp4).css({
                		"-webkit-transform":"translate3d(0, 0, 0)"
                    });
                };
                // mp4.onloadstart = function(e){
                // 	$.alert("视频开始加载")
                // 	// $.alert(e)
                // };
                // mp4.ondurationchange = function(){
                // 	$.alert("视频的时长已改变");
                // };
                // mp4.onloadedmetadata = function(){
                // 	$.alert("视频的元数据已加载");
                // };
                // mp4.onloadeddata = function(){
                // 	$.alert("前帧的数据是可用的");
                // };
                // mp4.onprogress = function(){
                // 	// $.alert("视频正在下载中");
                // };
                mp4.oncanplay = function(){
                    // $.alert("视频已准备好开始播放");
                    mp4.controls = true;
                    $(mp4).css({
                        "-webkit-transform":"translate3d(0, 0, 0)"
                    });
                };
                // mp4.oncanplaythrough = function(){
                // 	$.alert("视频能够不停顿地一直播放")
                // };

                window.beforeunload = function(){
                    mp4.setAttribute("src","");
                    $(videoBox).remove();
                    return true;
                };
            }

            $(".video2").html(videoBox);
            $(".intro").html(gm.replace(tmp, data.value));

            /*gm.lecture.videoComment(data);*/


            //gm.pul.setTitle("讲堂-" + data.videoInfo.title);
        }else{
            components.alert(data.message);
        }
    }
    var pageno=1;
    var totalpage=0;
    /*//新增评论接口
    gm.common.videoComment(token,1,getcomment);*/
    //获取视频评论
    gm.common.getVideoComment(vedioid,1,1,10,getcomment);

    //新增评论接口的回调
    function getcomment(data){
        if(!data){
            components.alert("服务器出错!");
        }
        if(data.code=="2000"){
            var _arr=loadCommentStr(data);
            $(".lecture_comment ul").html(_arr.join(''));
            totalpage=data.total;//总页数
            if(data.value.length>9){
                loadMoreComment();
            }else{
                $("#play_loadMoreComment").hide();
            }
        }else{
            //components.alert(data.message);
            if(!gm.common.isObjUsable(token)){
                $(".lecture_comment,.receive").css({"display":"none"});

            }

        }
    }

    var _gflag = false;

    //获取医生个人信息
    gm.doctor.getUserInfo(function(data){
        $(".video2").attr("value",data.doctorId);
    });

    //添加评论接口
    $(".receive .btn-def").bind({
        touchend:function(){
            //判断是否已经登录
            if(!gm.common.isObjUsable(token)){
                gm.pul.toUrl("goodm://login");
                return;
            }
            var _p = $(".receive input").val();
            var userid=$(".video2").attr("value");
            gm.common.addPlatformCommunication(vedioid,1,userid,_p,function(data){
                if(data.code=="2000"){//刷新评论列表
                    //清除输入框内容
                    $(".ipt-def").val("");
                    $(".ipt-def").blur();
                    gm.common.getVideoComment(vedioid,1,1,10,getcomment);
                }
            });
        }
    });
    //防止表单提交
    $("form").bind({
        submit:function(e){
            return false;
        }
    });





    /**
     * 加载更多评论
     *
     */
    function loadMoreComment(){

        $("#play_loadMoreComment").bind({
            touchend:function(){
                ++pageno;
                gm.common.getVideoComment(vedioid,1,pageno,10,function(data){
                    if(!data){
                        components.alert("服务器出错!");
                    }
                    if(data.code=="2000"){
                        var _arr=loadCommentStr(data);
                        $(".lecture_comment ul").append(_arr.join(''));
                        totalpage=data.total;//总页数
                        if(data.value.length>0){
                            loadMoreComment();
                        }else{
                            $("#play_loadMoreComment").unbind().html("没有更多评论了！");
                        }
                    }else{
                        //components.alert(data.message);
                        if(!gm.common.isObjUsable(token)){
                            $(".lecture_comment,.receive").css({"display":"none"});

                        }

                    }
                });
            }
        });
    }

    /**
     * 评论内容的拼接
     * @param data
     */
    function loadCommentStr(data){
        var _tmp = '<li class="comcon">\
                            <div class="comcon_content">\
                                <div class="comcon_header">\
                                    <img src={heahPath} />\
                                </div>\
                                <div class="comcon_text">\
                                    <span class="">{createTime}</span>\
                                    <p class="">{commentContent}</div>\
                            </div>\
                        </li>';
        var _arr = [];

        $(data.value).each(function(i,o){
            var getheadimg=gm.common.isObjUsable(o.heahPath);
            o.heahPath=getheadimg?window._interfaceImgPath+""+o.heahPath:gm.common.sexGetDoctorDefImg(o.sex);
            _arr.push(gm.replace(_tmp,o));
        });
        return _arr;
    }

    /**
     * 页面后退
     */
    gm.pul.returnurl=function(){
        var from=gm.para.get(window.location.href,"from");
        if(from=="refer_soul")
            gm.pul.toUrl("/patient/refer/refer_soul.shtml?rnd=4.373#b");
        else if(from=="collection")
            gm.pul.toUrl("/html/user/my_collection.shtml?from=collection");
        else//回去医生端
            history.go(-1);
    };
    /**
     * 分享调用
     */
    gm.doctor.tanchu=function (){
        var _ = $(this);
        var _title=$(".intro h2").html();
        var _img=$("#video").attr("poster")||getvedioimg;
        if(!gm.doctor.isLoginDoctor()){
            gm.pul.toUrl("goodm://login");
            return;
        }
        var _link=window._interfacePath + "/hxq/doctor/playing.html?vidoUuid=" + gm.para.get(window.location.href,"vidoUuid");
        var obj = {
            title:_title,//获取文章title
            desc:_title,//获取文章desc
            img:_img,//获取文章img
            link:_link
        };

        gm.share(obj,function(){
            /* $.getDate({
             page:"doctor",
             inter:"addDoctorShare",
             data:{contentUuid:contentUuid,doctorUuid:gm.user.getDoctor()},
             callback:function(data){	}
             }); */
        });
    }

});
